package librss;
import java.util.*;
import org.jdom.Element;
/*
 * RSSParser.java
 *
 * Created on March 7, 2009, 12:23 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author alvaro
 */
class RSSParser {
    private String fileName;
    private XMLHandler xml;
    /** Creates a new instance of RSSParser */
    RSSParser(String fileName) throws Exception {
        this.fileName = fileName;
        xml = new XMLHandler(fileName);
    }
    
    int getItemsNumber()throws Exception {
        List l = xml.selectNodes(xml.getDocument(), "/rss/channel/item");
        return l.size();
    }
    
    RSSItem getItemAt(int index) throws Exception {
        List l = xml.selectNodes(xml.getDocument(), "/rss/channel/item");
        Element el = (Element) l.get(index);
        List children = el.getChildren();
        RSSItem item = new RSSItem();
        for(int i = 0;i<children.size();i++){
            Element e = (Element) children.get(i);
            if(e.getName().equalsIgnoreCase("pubdate"))
                item.setPubDate(e.getText());
            if(e.getName().equalsIgnoreCase("category"))
                item.addTag(e.getText());
            if(e.getName().equalsIgnoreCase("title"))
                item.setTitle(e.getText());
            if(e.getName().equalsIgnoreCase("description"))
                item.setDescription(e.getText());
            if(e.getName().equalsIgnoreCase("link"))
                item.setLink(e.getText());
            if(e.getName().equalsIgnoreCase("author"))
                item.setAuthor(e.getText());
        }
        return item;
    }
    
    RSSItem getNewestItem() throws Exception {
        return this.getItemAt(0);
    }
    
    Iterator<RSSItem> getIterator() throws Exception {
        return this.getVector().iterator();
    }
    
    Vector<RSSItem> getVector() throws Exception {
        Vector<RSSItem> vec = new Vector<RSSItem>();
        for(int i = 0;i<this.getItemsNumber();i++){
            vec.add(this.getItemAt(i));
        }
        return vec;
    }
    
}
